package com.example.file_upload.service.impl;

import com.example.file_upload.service.FileService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.UUID;

@Service
public class FileServiceImpl implements FileService {
    @Value("${file.upload-dir}")
    private String uploadDir;//将读取到的file.upload-dir赋值给uploadDir

    //单文件上传
    @Override()
    public String saveFile(MultipartFile file) throws IOException {
        Path uploadPath=Path.of(uploadDir);
        if (!Files.exists(uploadPath)){
            Files.createDirectories(uploadPath);
        }
        //生成一个唯一的文件名
        String uniqueFileName= UUID.randomUUID()+"_"+file.getOriginalFilename();
        Path filePath=uploadPath.resolve(uniqueFileName);
        file.transferTo(filePath);

        return filePath.toString();
    }


    //多文件上传=N次单文件上传
    @Override
    public String saveMultiparFile(MultipartFile[] files) throws IOException {
        //保存多文件上传路径
        StringBuilder result=new StringBuilder();
        //遍历上传文件数组，进行单文件上传操作
        for (MultipartFile file : files){
            result.append(saveFile(file)).append(",");
        }
        return result.toString().trim();
    }

    //下载文件功能
    @Override
    public Path getFilePath(String fileName) {
        return Paths.get(uploadDir+"/"+fileName);
    }
}
